import React from 'react';
import { Tabs, Card, Radio, Input, Button, message } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import Editor from '@/utils/Editor';
import UserTypeModal from './userTypeModal';
import styles from './index.less';

class Welcome extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      activeKey: 'default',
      welcomeList: []
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  initInfo = welcomeList => {
    const arr = [];
    for (const item of welcomeList) {
      if (item.welcomeType === 1) {
        item.welcomeEditor = item.welcomeContent;
      };
      if (item.welcomeType === 2) {
        item.welcomeInput = item.welcomeContent;
      };
      arr.push(item);
    };
    this.setState({ welcomeList: arr });
  }

  changeTabPane = (key) => {
    if (key === 'plus') {
      let { welcomeList } = this.state;
      this.UserTypeModal.openModal(welcomeList);
    } else {
      this.setState({ activeKey: key });
    }
  }

  /* 删除用户类型的个性化欢迎语 */
  editPane = (targetKey, action) => {
    console.log(targetKey, action);
    if (action === 'remove') {
      let { welcomeList } = this.state;
      const newList = welcomeList.filter(item => item.userTypeId != targetKey);
      this.setState({ welcomeList: newList, activeKey: newList[0].userTypeId });
    }
  }

  /* 修改欢迎语类型 */
  changeWelcomeType = (e, index) => {
    let { welcomeList } = this.state;
    welcomeList[index].welcomeType = e.target.value;
    this.setState({ welcomeList });
  }

  /* 修改以问题的答案作为欢迎语 */
  changeWelcomeInput = (e, index) => {
    let { welcomeList } = this.state;
    welcomeList[index].welcomeInput = e.target.value;
    this.setState({ welcomeList });
  }

  /* 修改欢迎语问题 */
  changeQuestion = (e, questionIndex, paneIndex) => {
    let { welcomeList } = this.state;
    welcomeList[paneIndex].questionList[questionIndex] = e.target.value;
    this.setState({ welcomeList });
  }

  /* 上移欢迎问题 */
  upQuestion = (questionIndex, paneIndex) => {
    let { welcomeList } = this.state;
    let questions = welcomeList[paneIndex].questionList;
    questions[questionIndex] = questions.splice(questionIndex - 1, 1, questions[questionIndex])[0];
    welcomeList[paneIndex].questionList = questions;
    this.setState({ welcomeList });
  }

  /* 删除欢迎问题 */
  removeQuestion = (questionIndex, paneIndex) => {
    let { welcomeList } = this.state;
    let questions = welcomeList[paneIndex].questionList;
    const newQuestions = questions.filter((item, index) => index != questionIndex);
    welcomeList[paneIndex].questionList = newQuestions;
    this.setState({ welcomeList });
  }

  /* 新增欢迎问题 */
  addQuestion = (index) => {
    let { welcomeList } = this.state;
    let questions = welcomeList[index].questionList;
    for (const item of questions) {
      if (!item) {
        message.error(formatMessage({ id: 'account.robotSetup.welcome.emptyQuestionError' }));
        return false;
      }
    };
    if (questions.length < 10) {
      questions.push('');
      welcomeList[index].questionList = questions;
      this.setState({ welcomeList, }, () => {
        const { input } = this.inputRef;
        input.focus();
        input.setSelectionRange(0, input.value.length);
      });
    } else {
      message.error(formatMessage({ id: 'account.robotSetup.welcome.maxQuestionsError' }));
    }
  }

  /* 新增用户类型的个性欢迎语 */
  addPersonalWelcome = list => {
    let { welcomeList } = this.state;
    welcomeList.push(...list);
    this.setState({ welcomeList });
  }

  getWelcomeList = () => {
    let { welcomeList } = this.state;
    let obj = {
      welcome: '', //默认欢迎语
      welcomeType: 1,//默认欢迎语类型
      questionList: [],//默认欢迎语问题
      personalizedWelcome: []//其他用户类型的个性欢迎语
    };
    for (const i in welcomeList) {
      const item = welcomeList[i];
      //获取欢迎语
      //1.欢迎语类型为1（用以下内容作为欢迎语），则取Ueditor的内容，若取不到Ueditor对象，则表示添加了用户类型后没有打开过这个tab，则直接取welcomeContent，因为新增的时候已经添加默认的欢迎话术
      //2.欢迎语类型为2（用以下问题的答案作为欢迎语），则取welcomeInput的值
      if (item.welcomeType === 1) {
        const con = `content${i}`;
        item.welcomeContent = this.refs[con] ? this.refs[con].getUeditorContent() : item.welcomeContent;
      } else if (item.welcomeType === 2) {
        item.welcomeContent = item.welcomeInput;
      };
      // console.log(item.questionList);
      //获取欢迎语问题（去除内容为空的数据）
      const newQuestions = item.questionList.filter(questionItem => questionItem != '');
      item.questionList = newQuestions ? newQuestions : [];

      //整合数据 将默认欢迎语和其他用户类型的个性欢迎语区分开
      if (item.userTypeId === 'default') {
        obj.welcome = item.welcomeContent;
        obj.welcomeType = item.welcomeType;
        obj.questionList = item.questionList
      } else {
        //去掉welcomeEditor welcomeInput两个辅助字段
        // delete item.welcomeEditor
        // delete item.welcomeInput
        obj.personalizedWelcome.push(item);
      }
    };
    // console.log(obj);
    return obj;
  }

  render() {
    const { activeKey, welcomeList } = this.state;
    return (
      <div className={styles.welcomes}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: '16px' }}>
          <span style={{ width: '3px', height: '16px', background: '#4B5475', display: 'inline-block' }}></span>
          <span style={{ margin: '0 16px 0 10px', fontWeight: 'bold', color: '#333333' }}>{formatMessage({ id: 'account.robotSetup.welcome.title' })}</span>
          {/* <span style={{ fontSize: '13px', fontWeight: '400', color: '#33333380' }}>{formatMessage({ id: 'account.robotSetup.welcome.invalidTip' })}</span> */}
        </div>
        <Tabs
          type="editable-card"
          hideAdd
          onChange={this.changeTabPane}
          activeKey={activeKey}
          tabBarStyle={{ marginBottom: 0 }}
          onEdit={this.editPane}
        >
          {welcomeList.map((pane, index) => (
            <Tabs.TabPane tab={pane.userTypeId === 'default' ? formatMessage({ id: 'account.robotSetup.welcome.defaultWelcome' }) : pane.userTypeName} key={pane.userTypeId} closable={pane.userTypeId != 'default'}>
              <Card bordered={false} bodyStyle={{ border: '1px solid #e8e8e8', borderTop: 0 }}>
                <Radio.Group onChange={(e) => this.changeWelcomeType(e, index)} value={pane.welcomeType}>
                  <Radio value={1}>{formatMessage({ id: 'account.robotSetup.welcome.contentAsWelcome' })}</Radio>
                  <Radio value={2}>{formatMessage({ id: 'account.robotSetup.welcome.answerAsWelcome' })}</Radio>
                </Radio.Group>
                <div style={{ width: 600, marginTop: 10 }}>
                  {pane.welcomeType == 1 ? (
                    <Editor
                      content={pane.welcomeEditor ? pane.welcomeEditor : ''}
                      name={`content${index}`}
                      id={`content${index}`}
                      ref={`content${index}`}
                      zIndex={9}
                    />
                  ) : (
                    <Input
                      onChange={(e) => this.changeWelcomeInput(e, index)}
                      placeholder=""
                      maxLength={200}
                      value={pane.welcomeInput ? pane.welcomeInput : ''}
                    />
                  )}
                </div>
                {/* <div style={{ margin: '10px 0' }}>欢迎语问题</div> */}
                {/* {pane.questionList.map((questionItem, questionIndex) => {
                  return (
                    <div key={questionIndex} style={{ marginBottom: 10 }}>
                      <Input
                        value={questionItem}
                        onChange={(e) => this.changeQuestion(e, questionIndex, index)}
                        style={{ width: '80%' }}
                        maxLength={200}
                        onPressEnter={() => this.addQuestion(index)}
                        ref={input => (this.inputRef = input)}
                      />
                      {
                        questionIndex != 0 ? (
                          <Icon
                            type="arrow-up"
                            style={{ marginLeft: 10 }}
                            onClick={() => this.upQuestion(questionIndex, index)}
                          />
                        ) : null
                      }
                      <Icon
                        type="delete"
                        style={{ marginLeft: 10 }}
                        onClick={() => this.removeQuestion(questionIndex, index)}
                      />
                    </div>
                  )
                })} */}
                {/* <Button icon={'plus-circle'} type="link" onClick={() => this.addQuestion(index)}>添加</Button> */}
              </Card>
            </Tabs.TabPane>
          ))}
          <Tabs.TabPane tab={'+'} key={'plus'} closable={false} />
        </Tabs>

        <UserTypeModal onRef={ref => this.UserTypeModal = ref} addPersonalWelcome={this.addPersonalWelcome} />
      </div>
    );
  }
}

export default Welcome;
